# -*- coding: utf-8 -*-
from universal.common_header import *
from universal.common_header_widget import *
from universal.widget_common import createFilePathWidget_NObutton, Tasklistwidget
from Module.xRayDetection.xray.logs import Logger
class MainWindow_(QWidget):
    def __init__(self, w):
        super(MainWindow_, self).__init__()
        self.window = w
        self.initlogs = init_log()
        self.width = 800
        self.height = 550
        # 设置主界面标题
        self.setWindowTitle("选择您的创建工程方式")
        # 设置固定尺寸
        self.setFixedSize(self.width, self.height)
        self.projectListShowed = False
        self.Pro_task = "目标检测"
        self.saveProDir = ''
        # self.activateWindow()
        self.init_widget()

    def init_widget(self):
        self.image_widget1 = QWidget(self)  # 设置左边New_project界面
        self.image_widget1.setGeometry(QRect(0, 0, 530, 550))
        self.Pro_LeftWidget()
        self.Pro_RightWidget()

    def Pro_LeftWidget(self):
        try:
            self.layout = QVBoxLayout(self.image_widget1)  # 垂直布局
            self.label = QLabel('     New Project')  # 设置标题
            self.label.setFont(QFont("Arial", 20))
            self.label.setAlignment(Qt.AlignCenter)

            imgspathLabel1, self.imgspathLineEdit1, imgspathLayout1, imgspathContainer1 = createFilePathWidget_NObutton(
                self, 'Name:')  # 设计第一行内容
            default_imgname = 'OD_Platform'
            self.imgspathLineEdit1.setText(default_imgname)
            proPathLabel, self.proPathEdit, proPathLayout, proPathContainer = createFilePathWidget_NObutton(self,
                                                                                                            'Path  :')  # 设计第二行内容
            act = QAction(self)
            act.setIcon(QIcon(':/icons/1-1.ico'))  # 待修改
            act.triggered.connect(lambda: self.getWeightsFile())
            self.proPathEdit.addAction(act, QLineEdit.TrailingPosition)
            default_proPath = os.path.expanduser('~')
            self.proPathEdit.setText(default_proPath)
            # ==========================水平布局设置Task列表图=====================
            self.contentsWidget = Tasklistwidget()
            self.createIcons()
            list_widget_conatiner = QWidget()
            label1 = QLabel("Task : ")
            label1.setAlignment(Qt.AlignRight | Qt.AlignTop)
            label1.setFont(QFont("Arial", 11))
            list_widget_ = QHBoxLayout(list_widget_conatiner)
            list_widget_.setSpacing(0)  # setSpacing表示控件的上下间距 setMargin表示控件的左右间距
            list_widget_.setContentsMargins(0, 2, 0, 2)
            list_widget_.addWidget(label1)
            list_widget_.addWidget(self.contentsWidget, Qt.AlignRight)
            # ==========================水平布局两个按钮=====================
            self.helpButton = QPushButton('Help')  # 设置帮助按钮
            self.helpButton.setFont(QFont("Arial", 10))
            self.helpButton.clicked.connect(self.Helpmessage)
            self.CreateButton = QPushButton('Create')  # 设置创建按钮
            self.CreateButton.setFont(QFont("Arial", 10))
            self.CreateButton.clicked.connect(self.createButton)
            ButtonLayout = QHBoxLayout()
            ButtonLayout.setSpacing(0)  # setSpacing表示控件的上下间距 setMargin表示控件的左右间距
            ButtonLayout.setContentsMargins(0, 2, 0, 2)
            ButtonLayout.addWidget(self.helpButton, 50, Qt.AlignRight)
            ButtonLayout.addWidget(self.CreateButton, 12, Qt.AlignRight)
            # ==========================================================
            self.layout.addWidget(self.label)
            self.layout.addWidget(imgspathContainer1)
            self.layout.addWidget(proPathContainer)
            self.layout.addWidget(list_widget_conatiner)
            self.layout.addLayout(ButtonLayout)

        except Exception as e:
            print(str(e))
            self.initlogs.log(Logger.ERROR, str(e), exception=True)

    def Pro_RightWidget(self):
        try:
            self.image_widget2 = QWidget(self)
            self.image_widget2.setGeometry(QRect(530, 0, 270, 550))  # 开始的横坐标，纵坐标，长，宽 ,[a(0)+a(2)=width]
            self.layout2 = QVBoxLayout(self.image_widget2)  # 垂直布局
            self.OpenButton = QPushButton('OpenProject')  # 设置按钮
            self.OpenButton.setFont(QFont("Arial", 12))
            self.modegroupBox = QGroupBox("")
            self.layout_Box = QVBoxLayout(self.modegroupBox)
            self.labelRecent = QLabel('Recent Project')  # 设置标题
            self.labelRecent.setFont(QFont("Arial", 11))
            self.labelRecent.setAlignment(Qt.AlignTop)
            # =======近期工程列表======
            self.txtWidget = QListWidget()
            self.txtWidget.setFont(QFont("Arial", 10))
            self.txtWidget.setContentsMargins(0, 2, 0, 2)
            self.recentProjectList = []

            if self.projectListShowed == False:
                recentpro = dir_root() + os.sep + 'Config/recentProject.txt'
                if not os.path.exists(recentpro):
                    open(recentpro, 'w')
                with open(recentpro, 'r') as f:
                    self.recentProjectList = f.readlines()
                self.recentProjectList = [x.split('\n')[0] for x in self.recentProjectList]
                for i in range(len(self.recentProjectList)):
                    pro = self.recentProjectList[i]
                    self.item = QListWidgetItem()
                    self.item.setForeground(Qt.black)  # 字体颜色
                    self.item.index = i
                    self.item.setFont(QFont('Arial', 12))
                    self.item.setSizeHint(QSize(self.txtWidget.width(), 25))
                    if i % 2 == 0:
                        self.item.setBackground(Qt.gray)  # 字体颜色背景
                    else:
                        self.item.setBackground(Qt.lightGray)
                    self.item.setText(pro.split('\\')[-1].split('/')[-1].split('.')[0])
                    self.txtWidget.addItem(self.item)
                    self.txtWidget.setAutoFillBackground(True)
                    self.txtWidget.setStyleSheet("background-color:rgb(25,35,45)")

            self.txtWidget.itemDoubleClicked.connect(self.choseRecentProject)
            self.layout_Box.addWidget(self.labelRecent)
            self.layout_Box.addWidget(self.txtWidget)
            self.layout2.addWidget(self.OpenButton)
            self.layout2.addWidget(self.modegroupBox)
            self.OpenButton.clicked.connect(self.openProject)
        except Exception as e:
            print(str(e))
            self.initlogs.log(Logger.ERROR, str(e), exception=True)

    def deleteTxtWidgetItem(self):
        try:
            self.txtWidget.takeItem(self.txtWidget.currentRow())
        except Exception as e:
            print(str(e))
            self.initlogs.log(Logger.ERROR, str(e), exception=True)

    def CreateClass(self, Jpg_Path, className):
        try:
            a1Button = QListWidgetItem(self.contentsWidget)
            a1Button.setIcon(QIcon(Jpg_Path))  # 待修改
            a1Button.setText(className)
            a1Button.setTextAlignment(Qt.AlignHCenter)
            a1Button.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
            return a1Button
        except Exception as e:
            print(str(e))
            self.initlogs.log(Logger.ERROR, str(e), exception=True)

    def createIcons(self):
        try:
            a1Button = self.CreateClass(':/icons/1.jpg', '图像分类')
            a2Button = self.CreateClass(':/icons/2.jpg', "目标检测")
            a3Button = self.CreateClass(':/icons/3.jpg', "语义分割")
            a4Button = self.CreateClass(':/icons/4.jpg', "实例分割")
            self.contentsWidget.currentItemChanged.connect(self.changePage)
            self.contentsWidget.setCurrentItem(a2Button)
        except Exception as e:
            print(str(e))
            self.initlogs.log(Logger.ERROR, str(e), exception=True)


    def changePage(self, current):
        try:
            aa = self.contentsWidget.currentItem()
            self.Pro_task = aa.text()
        except Exception as e:
            print(str(e))
            self.initlogs.log(Logger.ERROR, str(e), exception=True)

    def getWeightsFile(self):
        try:
            self.saveProDir = str(QFileDialog.getExistingDirectory(self,
                                                                   '章鱼博士',
                                                                   None,
                                                                   QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks))
            if self.saveProDir == '':
                return
            self.proPathEdit.setText(self.saveProDir)

        except Exception as e:
            print(str(e))
            self.initlogs.log(Logger.ERROR, str(e), exception=True)

    def Helpmessage(self):
        news_Helpmessage = '\n' + "新建工程:输入名字->设置路径->选择任务->点击创建" \
                           + '\n' + '\n' + "打开工程:点击OpenProject->选择工程路径" + \
                           '\n' + '\n' + "最近工程:如果近期工程列表有内容,双击即可打开"
        customMsgBox, cancelButton = news_box2(news_Helpmessage)
        button = customMsgBox.clickedButton()
        if button == cancelButton:
            return

    def createButton(self):
        try:
            name = self.imgspathLineEdit1.text()
            self.saveProDir = self.proPathEdit.text()
            self.DirPath = self.saveProDir + "/" + name

            if os.path.exists(self.DirPath):
                news_create = '此工程文件名字已经存在，请修改'
                customMsgBox, cancelButton = news_box2(news_create)
                button = customMsgBox.clickedButton()
                if button == cancelButton:
                    return

            self.window.clearWindow()
            os.makedirs(self.DirPath)
            self.PATH_ = self.DirPath + "/" + name + ".proj"
            self.close()

            self.window.showMaximized()
            self.window.show()
            self.window.projectTask = self.Pro_task
            self.window.xmlFilePath = self.PATH_
            self.window.newProject()
        except Exception as e:
            print(str(e))
            self.initlogs.log(Logger.ERROR, str(e), exception=True)

    def openProject(self):
        print('openProject')
        self.window.openMyProject('openPro')

    def choseRecentProject(self, render):
        self.window.xmlFilePath = self.recentProjectList[render.index]
        self.window.openMyProject('recentPro')


class HashableQListWidgetItem(QListWidgetItem):
    def __init__(self, *args):
        super(HashableQListWidgetItem, self).__init__(*args)

    def __hash__(self):
        return hash(id(self))